/*************************************************************************
	> File Name: tcp_client.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/02 14:34
 ************************************************************************/

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <unistd.h>

const int BUF_SIZE = 1024;

static void usage(std::string proc)
{
    std::cout << "Usage:" << proc << " ip port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        std::cout << "socket error" << std::endl;
        exit(1);
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    if (connect(sock, (struct sockaddr*)&server, sizeof server) < 0) {
        std::cerr << "connect error" << std::endl;
        exit(3);
    }
    std::cout << "connect success." << std::endl;
    char buffer[BUF_SIZE];
    while (1) {
        std::string messgeSend;
        std::cout << "Please input:";
        std::getline(std::cin, messgeSend);
        if (messgeSend == "quit") {
            break;
        }
        ssize_t s = send(sock, messgeSend.c_str(), messgeSend.size(), 0);
        if (s > 0) {
            memset(buffer, 0, sizeof buffer);
            ssize_t res = recv(sock, buffer, sizeof buffer - 1, 0);
            if (res > 0) {
                std::cout << buffer << std::endl;
            }
        } else {
            break;
        }
    }
    close(sock);
    return 0;
}
